import { Button } from 'antd'
import {
  WordsLibraryFilter,
  type FilterChildrenProps,
} from '@/desktop/components/words/library/filter'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import EditWords from './edit'
import { useEditWords, useSendWords } from './hooks'
import SendConfirm from './send'
import WordsItem from './words-item'

export default function WordsLibrary() {
  return <div css={s.wordsLibrary}>
    <WordsLibraryFilter RenderComponent={ListContent} />
  </div>
}

function ListContent({ wordsList, showGlobal }: FilterChildrenProps) {
  const [isAdmin] = useStreams(services.auth.isAdmin$)
  const { editing, edit, finishEdit, remove } = useEditWords()
  const { send, confirming: sendConfirming, confirmed: confirmSend, cancelConfirm } = useSendWords()
  const addable = !showGlobal || isAdmin === true

  return <>
    <main css={s.list}>
      {wordsList.map(words => <WordsItem
        key={words.id}
        words={words}
        edit={edit}
        remove={remove}
        send={send}
      />)}
    </main>

    <footer css={s.footer} className={addable ? 'show-add' : ''}>
      {showGlobal ? <div className="tips">仅管理员可创建和编辑全员话术</div> : null}
      {addable ? (
        <Button type="link" onClick={() => edit()}>
          创建新话术
        </Button>
      ) : null}
    </footer>

    <EditWords words={editing} isGlobal={showGlobal} onFinish={finishEdit} />
    <SendConfirm words={sendConfirming} send={confirmSend} onCancel={cancelConfirm} />
  </>
}

const s = {
  wordsLibrary: css`
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  `,
  list: css`
    flex: 1;
    overflow-y: auto;
    position: relative;
  `,
  footer: css`
    border-top: 1px solid #f0f0f0;
    font-size: 12px;
    padding: 8px 0;
    text-align: center;

    .tips {
      color: #999;
      padding: 8px 0;
    }
    &.show-add .tips {
      margin-top: -8px;
      padding: 0 0 12px;
    }
  `,
}
